<div class="standardContainer">
    <div class="ui basic segment">
        <h2>Default Site</h2>
        <p>Default routing options for inbound traffic</p>
        <div class="ui form">
            <div class="grouped fields">
                <label>What to show when Zoraxy is hit with an unknown Host?</label>
                <div class="field">
                    <div class="ui radio defaultsite checkbox">
                        <input type="radio" name="defaultsiteOption" checked="checked" value="webserver">
                        <label>Internal Static Web Server<br>
                            <small>Check this if you prefer a more Apache / Nginx like experience</small>
                        </label>
                    </div>
                </div>
                <div class="field">
                    <div class="ui radio defaultsite checkbox">
                        <input type="radio" name="defaultsiteOption" value="proxy">
                        <label>Reverse Proxy Target<br>
                            <small>Proxy the request to a target IP / domain</small>
                        </label>
                    </div>
                </div>
                <div class="field">
                    <div class="ui radio defaultsite checkbox">
                        <input type="radio" name="defaultsiteOption" value="redirect">
                        <label>Redirect<br>
                            <small>Redirect the user to a new location</small>
                        </label>
                    </div>
                </div>
                <div class="field">
                    <div class="ui radio defaultsite checkbox">
                        <input type="radio" name="defaultsiteOption" value="notfound">
                        <label>Show 404 NOT FOUND<br>
                            <small>Respond to request with a 404 page</small>
                        </label>
                    </div>
                </div>
                <div class="field">
                    <div class="ui radio defaultsite checkbox">
                        <input type="radio" name="defaultsiteOption" value="closeresp">
                        <label>Close Connection<br>
                            <small>Close the connection without any response</small>
                        </label>
                    </div>
                </div>
            </div>
        </div>

        <!-- Reverse Proxy as Default Site Options -->
        <div id="defaultSiteProxyOptions" class="ui basic segment advanceoptions defaultSiteOptionDetails" style="display:none; ">
            <div class="ui form">
                <div class="field">
                        <label>Reverse Proxy Target</label>
                        <input type="text" id="proxyRoot" onchange="checkRootRequireTLS(this.value);">
                        <small>e.g. localhost:8080 / 192.168.0.100:80 / example.com</small>
                </div>
                <div class="field">
                    <div class="ui checkbox">
                        <input type="checkbox" id="rootReqTLS">
                        <label>Reverse proxy target require TLS connection <br><small>Check this if your proxy target URL require connection with https://</small></label>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Redirect as default site Options-->
        <div id="defaultSiteRedirectOptions" class="ui basic segment advanceoptions defaultSiteOptionDetails" style="display:none;"">
            <div class="ui form">
                <div class="field">
                    <label>Redirect target domain</label>
                    <div class="ui input">
                        <input id="redirectDomain" type="text" placeholder="http://example.com">
                    </div>
                    <small>Unset subdomain will be redirected to the link above. Remember to include the protocol (e.g. http:// or https://)</small>
                </div>
            </div>
        </div>

        <button class="ui basic button" onclick="setProxyRoot(this)"><i class="green checkmark icon" ></i> Apply Changes</button>
        <button class="ui basic button" onclick="initRootInfo()"><i class="refresh icon" ></i> Reset</button>
        <br>
    </div>
</div>
<script>
    var currentDefaultSiteOption = 0; //For enum see typedef.go
    $("#advanceRootSettings").accordion();

    //Handle toggle events of option radio boxes
    function updateAvaibleDefaultSiteOptions(){
        let selectedDefaultSite = $('input[name="defaultsiteOption"]:checked').val();

        $(".defaultSiteOptionDetails").hide();
        $("#useRootProxyRouterForVdir").parent().addClass("disabled");
        if (selectedDefaultSite == "webserver"){
            //Use build in web server as target
            let staticWebServerURL = "127.0.0.1:" + $("#webserv_listenPort").val();
            $("#proxyRoot").val(staticWebServerURL);
            $("#proxyRoot").parent().addClass("disabled");
            $("#rootReqTLS").parent().checkbox("set unchecked");
            $("#rootReqTLS").parent().addClass("disabled");
            $("#useRootProxyRouterForVdir").parent().removeClass("disabled");
            currentDefaultSiteOption = 0;
        }else if (selectedDefaultSite == "proxy"){
            $("#defaultSiteProxyOptions").show();
            $("#rootReqTLS").parent().removeClass("disabled");
            $("#proxyRoot").parent().removeClass("disabled");
            $("#useRootProxyRouterForVdir").parent().removeClass("disabled");
            currentDefaultSiteOption = 1;
        }else if (selectedDefaultSite == "redirect"){
            $("#defaultSiteRedirectOptions").show();
            currentDefaultSiteOption = 2;
        }else if (selectedDefaultSite == "notfound"){
            currentDefaultSiteOption = 3;
        }else if (selectedDefaultSite == "closeresp"){
            currentDefaultSiteOption = 4;
        }else{
            //Unknown option
            return;
        }

    }

    //Bind events to the radio boxes
    function bindDefaultSiteRadioCheckboxEvents(){
        $('input[type=radio][name=defaultsiteOption]').off("change").on("change", function() {
            updateAvaibleDefaultSiteOptions();
        });
    }
    
    function initRootInfo(callback=undefined){
        $.get("/api/proxy/list?type=root", function(data){
            if (data == null){
                msgbox("Default site load failed", false);
            }else{
                var $radios = $('input:radio[name=defaultsiteOption]');
                let proxyType = data.DefaultSiteOption;
                //See typedef.go for enum conversion
                if (proxyType == 0){
                    $radios.filter('[value=webserver]').prop('checked', true);
                }else if (proxyType == 1){
                    $radios.filter('[value=proxy]').prop('checked', true);
                    $("#proxyRoot").val(data.DefaultSiteValue);
                }else if (proxyType == 2){
                    $radios.filter('[value=redirect]').prop('checked', true);
                    $("#redirectDomain").val(data.DefaultSiteValue);
                }else if (proxyType == 3){
                    $radios.filter('[value=notfound]').prop('checked', true);
                }else if (proxyType == 4){
                    $radios.filter('[value=closeresp]').prop('checked', true);
                }
                updateAvaibleDefaultSiteOptions();
                
                $("#proxyRoot").val(data.ActiveOrigins[0].OriginIpOrDomain);
                checkRootRequireTLS(data.ActiveOrigins[0].OriginIpOrDomain);
            }

            if (callback != undefined){
                callback();
            }
        });
    }
    initRootInfo(function(){
        bindDefaultSiteRadioCheckboxEvents();
    });


    function isUsingStaticWebServerAsRoot(callback){
        let currentProxyRoot = $("#proxyRoot").val().trim();
        $.get("/api/webserv/status", function(webservStatus){
            if (currentProxyRoot == "127.0.0.1:" + webservStatus.ListeningPort || currentProxyRoot == "localhost:" + webservStatus.ListeningPort){
                return callback(true);
            }
            return callback(false);
        });
        
    }
    

    //Bind event to tab switch
    tabSwitchEventBind["setroot"] = function(){
        
    }

    //Check if the given domain will redirect to https
    function checkRootRequireTLS(targetDomain){
        //Trim off the http or https from the origin
        if (targetDomain.startsWith("http://")){
            targetDomain = targetDomain.substring(7);
            $("#proxyRoot").val(targetDomain);
        }else if (targetDomain.startsWith("https://")){
            targetDomain = targetDomain.substring(8);
            $("#proxyRoot").val(targetDomain);
        }
       $.cjax({
            url: "/api/proxy/tlscheck",
            method: "POST",
            data: {url: targetDomain},
            success: function(data){
                if (data.error != undefined){

                }else if (data == "https"){
                    $("#rootReqTLS").parent().checkbox("set checked");
                }else if (data == "http"){
                    $("#rootReqTLS").parent().checkbox("set unchecked");
                }
            }
       })
    }

    //Set the new proxy root (aka default site) option
    function setProxyRoot(btn=undefined){
        var newpr = $("#proxyRoot").val();
        if (newpr.trim() == "" && currentDefaultSiteOption == 0){
            //Fill in the web server info
            newpr = "127.0.0.1:" +  $("#webserv_listenPort").val();
            $("#proxyRoot").val(newpr);
        }

        var rootReqTls = $("#rootReqTLS")[0].checked;

        if (btn != undefined){
            $(btn).addClass("disabled");
        }

        //proxy mode or redirect mode, check for input values
        var defaultSiteValue = "";
        if (currentDefaultSiteOption == 1){
            if ($("#proxyRoot").val().trim() == ""){
                $("#proxyRoot").parent().addClass("error");
                return;
            }
            defaultSiteValue = $("#proxyRoot").val().trim();
            $("#proxyRoot").parent().removeClass("error");

        }else if (currentDefaultSiteOption == 2){
            if ($("#redirectDomain").val().trim() == ""){
                $("#redirectDomain").parent().addClass("error");
                return;
            }
            defaultSiteValue = $("#redirectDomain").val().trim();
            $("#redirectDomain").parent().removeClass("error");
        }

        //Create the endpoint by calling add
        $.cjax({
            url: "/api/proxy/add",
            data: {
                "type": "root", 
                "tls": rootReqTls, 
                "ep": newpr,
                "defaultSiteOpt": currentDefaultSiteOption,
                "defaultSiteVal":defaultSiteValue,
            },
            method: "POST",
            success: function(data){
                if (data.error != undefined){
                    msgbox(data.error, false, 5000);
                }else{
                    //OK
                    
                    initRootInfo(function(){
                        
                        //Check if WebServ is enabled
                        isUsingStaticWebServerAsRoot(function(isUsingWebServ){
                            if (isUsingWebServ){
                                //Force enable static web server
                                //See webserv.html for details
                                setWebServerRunningState(true);
                            }
                            
                            msgbox("Default Site Updated");
                        })
                    });
                    
                }

                if (btn != undefined){
                    $(btn).removeClass("disabled");
                }
            },
            error: function(){
                msgbox("Unknown error occured", false);
            }
        });

    }

</script>